import React, { Component } from 'react'

export default class App extends Component {
  state = {
    psw: '',
    city: 'sh',
    isAgree: true,
    hobby: [], //存储选中的爱好的value值
    sex: '',
  }


  // 函数柯里化
  handle = (name) => (e) => {
    // 如果操作的是复选框则获取checked,否则获取value
    const value =
      e.target.type === 'checkbox' ? e.target.checked : e.target.value
    this.setState({
      [name]: value,
    })
  }

  hobbyHandle = (e) => {
    // e.target就是操作的那个复选框
    // 判断当前操作的复选框是否被选中,如果选中,则将这个复选框的value值添加到hobby数组中,否则从数组中删除
    const value = e.target.value
    if (e.target.checked) {
      // 选中了,添加
      this.state.hobby.push(value)
    } else {
      // 没选中,则删除
      const newHobby = this.state.hobby.filter((item) => {
        return item !== value
      })

      this.state.hobby = newHobby
    }
    this.setState({
      hobby: this.state.hobby,
    })
  }
  render() {
    return (
      <div>
        <input
          type="password"
          value={this.state.psw}
          onChange={this.handle('psw')}
          name="psw"
        />
        <select
          name=""
          id=""
          value={this.state.city}
          onChange={this.handle('city')}
        >
          <option value="bj">北京</option>
          <option value="sz">深圳</option>
          <option value="sh">上海</option>
        </select>
        <input
          type="checkbox"
          checked={this.state.isAgree}
          onChange={this.handle('isAgree')}
        />
        <br />
        ====================================================================={' '}
        <br />
        爱好: <br />
        抽烟:
        <input type="checkbox" value="smoking" onChange={this.hobbyHandle} />
        喝酒:
        <input type="checkbox" value="drinking" onChange={this.hobbyHandle} />
        找富婆:
        <input type="checkbox" value="findMoney" onChange={this.hobbyHandle} />
        <br />
        性别: <br />
        男:
        <input
          type="radio"
          name="sex"
          value="male"
          onChange={this.handle('sex')}
        />
        女:
        <input
          type="radio"
          name="sex"
          value="female"
          onChange={this.handle('sex')}
        />
      </div>
    )
  }
}
